package com.drcoffee.drcoffeemall.util;

import com.drcoffee.drcoffeemall.entry.Order;
import com.drcoffee.drcoffeemall.entry.OrderAttachment;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

/**
 * 使用spring-boot-starter-mail发送邮件
 *
 * @author Shihao Zhou
 */
@Component
public class EmailUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public boolean sendEmailGo(Integer type, Order order, String toEmail, String code, File file) {
        String htmlContent = "";
        String title = "";
        if (type == 0) {
            //找回密码验证码
            title = "Reset the Dr.coffee Spare Parts Mall password";
            htmlContent = codeEmailHtmlStr(0, code);
        } else if (type == 1) {
            // 注册验证码
            title = "Register Dr.coffee Spare Parts Mall account";
            htmlContent = codeEmailHtmlStr(1, code);
        } else if (type == 2) {
            // 登录验证码
            title = "Login Dr.coffee Spare Parts Mall account";
            htmlContent = codeEmailHtmlStr(2, code);
        } else if (type == 3) {
            // 订单信息
            title = "Dr.coffee Spare Parts Mall Order";
            htmlContent = orderEmailHtmlStr(1);
        } else if (type == 4) {
            // 更改邮箱
            title = "Change Dr.coffee Accessories Store account email";
            htmlContent = codeEmailHtmlStr(2, code);
        } else if (type == 5) {
            // 业务接收
            title = "Dr.coffee Spare Parts Mall Order";
            htmlContent = orderEmailHtmlStr(2);
        }
        if (type == 3 || type == 5) {
            Object is_send = redisTemplate.opsForValue().get(toEmail + order.getCode());
            if (is_send == null) {
                System.out.println("======================== 未发送:" + toEmail + order.getCode() + " ,添加缓存开始发送========================");
                redisTemplate.opsForValue().set(toEmail + order.getCode(), true, 15L, TimeUnit.MINUTES);
                return sendEmail(toEmail, title, htmlContent, true, file);
            } else {
                return false;
            }
        } else {
            return sendEmail(toEmail, title, htmlContent, true, file);
        }
    }


    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return template;
    }

    /**
     * 发送邮件
     */
    public Boolean sendEmail(String toEmail, String subject, String content, Boolean isHtml, File file) {
        try {
            String from = "Dr.coffee<dmall@dr-coffee.com>";
            System.out.println("================================ 发送邮件 ================================");
            JavaMailSenderImpl javaMailSender = getJavaMailSenderImpl();
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper;
            mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(from);
            mimeMessageHelper.setTo(toEmail.split(","));
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(content, isHtml);
            if (file != null) {
                mimeMessageHelper.addAttachment(file.getName(), file);
            }
            javaMailSender.send(mimeMessage);
            System.out.println("================================ Sending the email succeeded ================================");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static JavaMailSenderImpl getJavaMailSenderImpl() {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setHost("smtp-n.global-mail.cn");
        javaMailSender.setUsername("dmall@dr-coffee.com");
        javaMailSender.setPassword("Zhoush1609@ZSH");
        javaMailSender.setPort(465);

        Properties javaMailProperties = new Properties();
        javaMailProperties.put("mail.smtps.timeout", "50000");

        //加认证机制
        javaMailProperties.put("mail.smtp.starttls.enable", true);
        javaMailProperties.put("mail.transport.protocol", "smtps"); // 启用smtps方式

        javaMailSender.setJavaMailProperties(javaMailProperties);
        javaMailSender.setDefaultEncoding("GBK");

        javaMailSender.setProtocol("smtps");// 发送协议smtps
        return javaMailSender;
    }

    public static String codeEmailHtmlStr(Integer type, String code) {
        String text_01 = "";
        String text_02 = "";
        String text_03 = code;
        String text_04 = "";
        if (type == 0) {
            text_01 = "Reset the password of Dr.coffee Spare Parts Mall";
            text_02 = "You are resetting your password, verification code:";
            text_04 = "The verification code is valid for 15 minutes. Do not disclose it.";
        } else if (type == 1) {
            text_01 = "Register Dr.coffee Spare Parts Mall account";
            text_02 = "You are registering an account, verification code:";
            text_04 = "The verification code is valid for 15 minutes. Do not disclose it.";
        } else if (type == 2) {
            text_01 = "Login Dr.coffee Spare Parts Mall account";
            text_02 = "You are logged into the Dr. Coffee Spare Parts Store, verification code:";
            text_04 = "The verification code is valid for 15 minutes. Do not disclose it.";
        } else if (type == 4) {
            text_01 = "Change Dr.coffee Accessories Store account email";
            text_02 = "You are changing your Dr.coffee Accessories Store account email, verification code:";
            text_04 = "The verification code is valid for 15 minutes. Do not disclose it.";
        }
        return "<div style=\"width: 100%;padding: 30px;\">\n" +
                "    <div\n" +
                "        style=\"box-sizing: border-box;width: 100%;margin: 0 auto;max-width: 508px;background-color: #FFFFFF;border: 1px solid #f6f6f6;box-shadow: 0px 0 10px rgba(0, 0, 0, 0.08);border-radius: 5px;\">\n" +
                "        <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"main-table\"\n" +
                "            style=\"width:100%;height:100%\"></table>\n" +
                "        <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"\n" +
                "            style=\"max-width: 508px; width: 100%; margin: 0 auto\">\n" +
                "            <tbody>\n" +
                "                <tr>\n" +
                "                    <td>\n" +
                "                        <div\n" +
                "                            style=\" text-align: center;padding-top: 20px; width: 100%; overflow: hidden;text-align: center; height: 100%;border-top-left-radius: 8px; border-top-right-radius: 8px; \">\n" +
                "                            <img style=\"width: 260px;\" src=\"https://www.dr-coffee.com/Uploadfiles/Picture/2022-6-29/20226292227234958.jpg\" />\n" +
                "                        </div>" +
                "                    </td>\n" +
                "                </tr>\n" +
                "            </tbody>\n" +
                "        </table>\n" +
                "        <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"logo-table\"\n" +
                "            style=\" max-width: 508px; width: 100%; background: #ffffff; margin: 50px auto 8px; \">\n" +
                "            <tbody>\n" +
                "                <tr>\n" +
                "                    <td style=\"padding: 0 24px;\">\n" +
                "                        <p\n" +
                "                            style=\" margin: 0 auto; font-family: HarmonyOS Sans, SF Pro Text, SF Pro Icons, robot, Helvetica Neue, Helvetica, Arial, sans-serif; font-style: normal; font-weight: 900; font-size: 18px; line-height: 130%; color: #363636; width: 100%; overflow-wrap: break-word; word-break: break-word; text-align: left; \">\n" +
                "                            " + text_01 +
                "                        </p>\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "            </tbody>\n" +
                "        </table>\n" +
                "        <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"logo-table\"\n" +
                "            style=\" max-width: 508px; width: 100%; margin: 0 auto; background: #ffffff\">\n" +
                "            <tbody>\n" +
                "                <tr>\n" +
                "                    <td style=\"text-align: center;padding: 0 24px\">\n" +
                "                        <p class=\"normal-font\"\n" +
                "                            style=\" margin: 0 auto; overflow-wrap: break-word; word-break: break-word; text-align: left; width: 100%; font-family: HarmonyOS Sans, SF Pro Text, SF Pro Icons, robot, Helvetica Neue, Helvetica, Arial, sans-serif; font-size: 14px; font-weight: 400; line-height: 150%; color: #000000; \">\n" +
                "                            <span class=\"bold-font\"\n" +
                "                                style=\" font-style: inherit; font-family: inherit; font-size: inherit; line-height: inherit; text-indent: inherit; letter-spacing: inherit; color:inherit; font-weight: 600; color: #363636;\">" + text_02 + "</span>\n" +
                "                        </p>\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "            </tbody>\n" +
                "        </table>\n" +
                "        <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"logo-table\"\n" +
                "            style=\" max-width: 508px; width: 100%; margin: 0 auto; background: #ffffff; margin-top: 12px\">\n" +
                "            <tbody>\n" +
                "                <tr>\n" +
                "                    <td style=\"padding: 0 24px;\">\n" +
                "                        <div class=\"code\"\n" +
                "                            style=\"letter-spacing:0.05em;padding-top: 30px;padding-bottom: 30px; font-size:48px;color:#000000;white-space:nowrap;font-style:normal;font-weight:600;text-align:center;font-family:HarmonyOS Sans, SF Pro Text, SF Pro Icons, robot, Helvetica Neue, Helvetica, Arial, sans-serif;color: #363636;\">\n" +
                "                            " + text_03 + "</div>\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "            </tbody>\n" +
                "        </table>\n" +
                "        <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"logo-table\"\n" +
                "            style=\" max-width: 508px; width: 100%; margin: 0 auto; background: #ffffff\">\n" +
                "            <tbody>\n" +
                "                <tr>\n" +
                "                    <td style=\"text-align: center;padding: 0 24px\">\n" +
                "                        <p class=\"normal-font\"\n" +
                "                            style=\" margin: 0 auto; overflow-wrap: break-word; word-break: break-word; text-align: left; width: 100%; font-family: HarmonyOS Sans, SF Pro Text, SF Pro Icons, robot, Helvetica Neue, Helvetica, Arial, sans-serif; font-size: 14px; font-weight: 400; line-height: 150%; color: #000000; \">\n" + text_04 +
                "                        </p>\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "            </tbody>\n" +
                "        </table>\n" +
                "        <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"logo-table\" style=\" width: 100%;\">\n" +
                "            <tbody>\n" +
                "                <tr>\n" +
                "                    <td style=\"text-align: center\">\n" +
                "                        <div\n" +
                "                            style=\" box-sizing: border-box; max-width: 508px; margin-top: 70px;background: #f9f9f9;  padding: 15px 24px 28px; border-bottom-left-radius: 8px; border-bottom-right-radius: 8px; overflow-wrap: break-word; word-break: break-word; text-align: center; font-size: 14px; font-family: HarmonyOS Sans, SF Pro Text, SF Pro Icons, robot, Helvetica Neue, Helvetica, Arial, sans-serif; font-weight: 400; color: #7d7d7d; line-height: 25px;\">\n" +
                "                            Address:No.3 Building,No.55 Taishan Road, New District, Suzhou\n" +
                "                            ,Jiangsu,China,215151<br>\n" +
                "                            Phone:0512-66800227 <br>\n" +
                "                            Customer service hotline:400-8977-711<br>\n" +
                "                            Email:<a style=\"text-decoration:none\" href=\"mailto:info@dr-coffee.com\" target=\"_blank\"\n" +
                "                                rel=\"noopener\">info@dr-coffee.com</a>\n" +
                "\n" +
                "                        </div>\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "            </tbody>\n" +
                "        </table>\n" +
                "    </div>\n" +
                "</div>";
    }

    public static String orderEmailHtmlStr(Integer type) {
        String text = "";
        if (type == 1) {
            text = "Order submitted successfully, please check the attachment for details!";
        } else if (type == 2) {
            text = "Hi，您有一个新的配件订单需要处理，详情请见附件，请前往配件商城后台尽快处理！";
        }
        String str_html = "<div style=\"width: 100%;padding: 30px;\">\n" +
                "    <div\n" +
                "        style=\"box-sizing: border-box;width: 100%;margin: 0 auto;max-width: 508px;background-color: #FFFFFF;border: 1px solid #f6f6f6;box-shadow: 0px 0 10px rgba(0, 0, 0, 0.08);border-radius: 5px;\">\n" +
                "        <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"main-table\"\n" +
                "            style=\"width:100%;height:100%\"></table>\n" +
                "        <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"\n" +
                "            style=\"max-width: 508px; width: 100%; margin: 0 auto\">\n" +
                "            <tbody>\n" +
                "                <tr>\n" +
                "                    <td>\n" +
                "                        <div\n" +
                "                            style=\" text-align: center;padding-top: 20px; width: 100%; overflow: hidden;text-align: center; height: 100%;border-top-left-radius: 8px; border-top-right-radius: 8px; \">\n" +
                "                            <img style=\"width: 260px;\" src=\"https://www.dr-coffee.com/Uploadfiles/Picture/2022-6-29/20226292227234958.jpg\" />\n" +
                "                        </div>" +
                "                    </td>\n" +
                "                </tr>\n" +
                "            </tbody>\n" +
                "        </table>\n" +
                "        <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"logo-table\"\n" +
                "            style=\" max-width: 508px; width: 100%; background: #ffffff; margin: 50px auto 8px; \">\n" +
                "            <tbody>\n" +
                "                <tr>\n" +
                "                    <td style=\"padding: 0 24px;\">\n" +
                "                        <p\n" +
                "                            style=\" margin: 0 auto; font-family: HarmonyOS Sans, SF Pro Text, SF Pro Icons, robot, Helvetica Neue, Helvetica, Arial, sans-serif; font-style: normal; font-weight: 900; font-size: 18px; line-height: 130%; color: #363636; width: 100%; overflow-wrap: break-word; word-break: break-word; text-align: left; \">\n" +
                "                            " + text +
                "                        </p>\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "            </tbody>\n" +
                "        </table>\n" +
                "        <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"logo-table\" style=\" width: 100%;\">\n" +
                "            <tbody>\n" +
                "                <tr>\n" +
                "                    <td style=\"text-align: center\">\n" +
                "                        <div\n" +
                "                            style=\" box-sizing: border-box; max-width: 508px; margin-top: 70px;background: #f9f9f9;  padding: 15px 24px 28px; border-bottom-left-radius: 8px; border-bottom-right-radius: 8px; overflow-wrap: break-word; word-break: break-word; text-align: center; font-size: 14px; font-family: HarmonyOS Sans, SF Pro Text, SF Pro Icons, robot, Helvetica Neue, Helvetica, Arial, sans-serif; font-weight: 400; color: #7d7d7d; line-height: 25px;\">\n" +
                "                            Address:No.3 Building,No.55 Taishan Road, New District, Suzhou\n" +
                "                            ,Jiangsu,China,215151<br>\n" +
                "                            Phone:0512-66800227 <br>\n" +
                "                            Customer service hotline:400-8977-711<br>\n" +
                "                            Email:<a style=\"text-decoration:none\" href=\"mailto:info@dr-coffee.com\" target=\"_blank\"\n" +
                "                                rel=\"noopener\">info@dr-coffee.com</a>\n" +
                "\n" +
                "                        </div>\n" +
                "                    </td>\n" +
                "                </tr>\n" +
                "            </tbody>\n" +
                "        </table>\n" +
                "    </div>\n" +
                "</div>";
        return str_html;
    }
}
